package cn.buk.qms.service;

import cn.buk.common.sc.CommonSearchCriteria;
import cn.buk.tms.entity.config.EnterpriseConfig;
import cn.buk.tms.entity.misc.FlightPriceCache;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created with IntelliJ IDEA.
 * User: yfdai
 * Date: 14-5-12
 * Time: 下午10:39
 * To change this template use File | Settings | File Templates.
 * @author yfdai
 */
@Component
public class FlightPolicyServiceImpl extends BaseFlightService implements FlightPolicyService {

    private final static Logger logger = LogManager.getLogger(FlightPolicyServiceImpl.class);

    @Override
    public int getCarrierCostPlus(final String carrier, final String entParam, final int defaultVal) {
        int retVal = defaultVal;

        if (entParam != null && entParam.trim().length() > 0) {
            String[] airlineCosts = entParam.split(";");
            if (airlineCosts.length > 0) {
                try {
                    retVal = Integer.parseInt(airlineCosts[0]);

                    for (int i = 1; i < airlineCosts.length; i++) {
                        String itemValue = airlineCosts[i];
                        if (!itemValue.substring(0, 2).equalsIgnoreCase(carrier)) {
                            continue;
                        }

                        String temp = itemValue.substring(3);
                        retVal = Integer.parseInt(temp);
                    }
                } catch (Exception ex) {
                }
            }
        }

        return retVal;
    }

    @Override
    public List<FlightPriceCache> searchFlightPriceCache(int enterpriseId, CommonSearchCriteria sc) {
        return flightPolicyDao.searchFlightPriceCache(enterpriseId, sc);
    }


    private String getOfficeNo(int enterpriseId) {
        return doGetEntCfg(enterpriseId, EnterpriseConfig.ENTERPRISE_TBOOKING_OFFICE);
    }

    private File doZip(String sourceFilename, String zipFileName) throws IOException {
        File file = new File(sourceFilename);
        File zipFile = new File(zipFileName);
        ZipOutputStream zos = null;
        try {
            // 创建写出流操作
            OutputStream os = new FileOutputStream(zipFile);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            zos = new ZipOutputStream(bos);

            zipFile(file, zos);
        } finally {
            if (zos != null) {
                zos.closeEntry();
                zos.close();
            }
        }

        return zipFile;
    }

    private void zipFile(File source, ZipOutputStream zos)
            throws IOException {

        InputStream is = null;
        byte[] buf = new byte[1024];
        int length;
        try {
            String pathName = source.getName();

            is = new FileInputStream(source);
            BufferedInputStream bis = new BufferedInputStream(is);
            zos.putNextEntry(new ZipEntry(pathName));
            while ((length = bis.read(buf)) > 0) {
                zos.write(buf, 0, length);
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }


    @Override
    public int importTicketNo(int enterpriseId, final String directory, String filename) {
        int retCode = 0;
        File target = new File(directory, filename);

        List<String> tickets = new ArrayList<>();

        try {
            FileInputStream fi = new FileInputStream(target);
            Workbook wb = new HSSFWorkbook(fi);
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum() + 1;
            logger.info("row: " + rowNum);
            for (int i = 1; i < rowNum; i++) {

                Row row = sheet.getRow(i);

                Cell cell = row.getCell(0);
                String cellValue = cell.getStringCellValue().trim();

                if (cellValue.length() == 14) {
                    //logger.info(":" + cellValue + ", " + cellValue.length());
                    cellValue = cellValue.substring(0, 13);
                    if (!tickets.contains(cellValue)) {
                        tickets.add(cellValue);
                    }
                } else if (cellValue.length() != 13) {
                    logger.info(":" + cellValue + ", " + cellValue.length());
                } else {
                    //tickets.add(cellValue);
                    if (!tickets.contains(cellValue)) {
                        tickets.add(cellValue);
                    }
                }
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            retCode = -1;
        }

        if (tickets.size() > 0) {
            logger.info("detr tickets: " + tickets.size());

            retCode = flightPolicyDao.createDetrTickets(enterpriseId, tickets);
        }

        return retCode;
    }

}
